package com.example.demo.util.http;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.BeanUtils;
import com.example.demo.util.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public <T> T httpGet(String url, HttpResponseListener<T> listener) {

        logger.info("HTTPClient GET 请求: {}", url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return listener.success(response);
            } else {
                return listener.fail(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T httpGet(String url, List<Header> headerList, HttpResponseListener<T> listener) {

        logger.info("HTTPClient GET 请求: {}", url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        if (headerList != null) {
            Header[] headers = new Header[headerList.size()];
            headerList.toArray(headers);
            httpGet.setHeaders(headers);
        }
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return listener.success(response);
            } else {
                return listener.fail(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T httpPost(String url, Object requestEntity, HttpResponseListener<T> listener) {
        logger.info("HTTPClient POST 请求: {}", url);
        String requestStr = null;
        if (requestEntity != null) {
            requestStr = JSONObject.toJSONString(requestEntity);
            logger.info("POST Body: {}", BeanUtils.objectPrint(requestEntity));
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
        try {
            if (StringUtils.isNotEmpty(requestStr)) {
                httpPost.setEntity(new StringEntity(requestStr, "utf-8"));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return listener.success(response);
            } else {
                return listener.fail(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T httpPost(String url, Object requestEntity, List<Header> headerList, HttpResponseListener<T> listener)  {
        logger.info("HTTPClient POST 请求: {}", url);
        String requestStr = null;
        if (requestEntity != null) {
            requestStr = JSONObject.toJSONString(requestEntity);
            logger.info("POST Body: {}", BeanUtils.objectPrint(requestEntity));
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (headerList != null) {
            Header[] headers = new Header[headerList.size()];
            headerList.toArray(headers);
            httpPost.setHeaders(headers);
        }
        try {
            if (StringUtils.isNotEmpty(requestStr)) {
                httpPost.setEntity(new StringEntity(requestStr, "utf-8"));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return listener.success(response);
            } else {
                return listener.fail(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * raw
     * @param url
     * @param requestStr
     * @param headerList
     * @param listener
     * @param <T>
     * @return
     */
    public <T> T httpsPost(String url, String requestStr, List<Header> headerList, HttpResponseListener<T> listener) {
        logger.info("HTTPClient POST(SSL) 请求: {}", url);
        logger.info("headerList: {}", headerList);
        logger.info("requestStr: {}", requestStr);
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpPost httpPost = new HttpPost(url);
        if (headerList != null) {
            Header[] headers = new Header[headerList.size()];
            headerList.toArray(headers);
            httpPost.setHeaders(headers);
        }
        CloseableHttpResponse response = this.request(httpClient, httpPost, requestStr);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return listener.success(response);
        } else {
            return listener.fail(response);
        }
    }

    private CloseableHttpResponse request(CloseableHttpClient httpClient, HttpPost httpPost, String requestStr) {
        CloseableHttpResponse response = null;
        try {
            if (StringUtils.isNotEmpty(requestStr)) {
                httpPost.setEntity(new StringEntity(requestStr, "utf-8"));
            }
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
